package com.example.pets_java.controller;

import com.example.pets_java.pojo.Article;
import com.example.pets_java.pojo.Comment;
import com.example.pets_java.pojo.Pet;
import com.example.pets_java.service.ArticleService;
import com.example.pets_java.service.CommentService;
import com.example.pets_java.service.PetService;
import com.example.pets_java.utils.SignatureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/pets")
public class PetController {

    @Autowired
    private PetService petService;

    @Autowired
    private WebClient webClient;

    @Autowired
    private SignatureUtil signatureUtil;


    @GetMapping("/owner/{ownerId}")
    public List<Pet> getPetsByOwnerId(@PathVariable int ownerId) {

        return petService.getPetsByOwnerId(ownerId);
    }

    @GetMapping("/owner")
    public List<Pet> getPetsForCurrentUser() {
        String userId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return petService.getPetsByOwnerId(Integer.parseInt(userId));
    }

    @GetMapping("/{id}")
    public Pet getPetById(@PathVariable int id) {
        Pet pet = petService.getPetById(id);
        if (pet == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found with id " + id);
        }
        return pet;
    }

    @PostMapping("/add")
    public void addPet(@RequestBody Pet pet) {
        petService.addPet(pet);
    }

    @PutMapping("/update")
    public void updatePet(@RequestBody Pet pet) {
        petService.updatePet(pet);
    }

    @DeleteMapping("/delete/{id}")
    public void deletePet(@PathVariable int id) {
        petService.deletePet(id);
    }

    @PostMapping("/chat")
    public Mono<Map<String, Object>> chatWithAI(@RequestBody Map<String, String> requestBody) {
        String content = requestBody.get("content");
        String sessionId = requestBody.get("sessionId");

        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("content", content);
        queryParams.put("sessionId", sessionId);

        return webClient.post()
                .uri(uriBuilder -> uriBuilder.path("/vivogpt/completions").build())
                .headers(headers -> headers.setAll(signatureUtil.generateAuthHeaders("POST", "/vivogpt/completions", queryParams)))
                .bodyValue(buildChatRequestBody(content, sessionId))
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {})
                .onErrorResume(e -> {
                    e.printStackTrace();
                    return Mono.error(new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Error processing chat request", e));
                });
    }

    private Map<String, Object> buildChatRequestBody(String content, String sessionId) {
        Map<String, Object> body = new HashMap<>();
        body.put("prompt", content);
        body.put("sessionId", sessionId);
        return body;
    }
}
